package com.example.muchentuner;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AlertDialog.Builder;

import com.airbnb.lottie.LottieAnimationView;
import com.example.muchentuner.ListenerFragment.TaskCallbacks;
import com.suke.widget.SwitchButton;

import android.os.Bundle;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

import java.util.Arrays;

public class ButtonActivity extends AppCompatActivity implements TaskCallbacks{

    public static final int RECORD_AUDIO_PERMISSION = 0;
    public static final String PREFS_FILE = "prefs_file";
    public static final String USE_SCIENTIFIC_NOTATION = "use_scientific_notation";
    public static final String CURRENT_TUNING = "current_tuning";
    protected static final String REFERENCE_PITCH = "reference_pitch";
    private static final String TAG_LISTENER_FRAGMENT = "listener_fragment";
    private static final String SWITCH_BUTTON_STATE ="switch_button_state";
    private static final String SWITCH_BUTTON_STATE2 ="switch_button_state2";

    private static boolean swiBtn_state=false;
    private static boolean swiBtn_state2=false;
    private static int tuningPosition = 0;
    private static int referencePitch;
    private static int referencePosition=0;//科学表示吧
    private static boolean isAutoModeEnabled = true;

    public static Tuning getCurrentTuning() {
        return TuningMapper.getTuningFromPosition(tuningPosition);//输入position，返回不同乐器的tuning对象
    }

    public static int getReferencePitch() {
        return referencePitch;
    }

    public static boolean isAutoModeEnabled() {
        return isAutoModeEnabled;
    }

    public static int getReferencePosition() {
        return referencePosition - 1; //to account for the position of the AUTO option
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);//矢量图片资源向后兼容
        setContentView(R.layout.activity_button);
        int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            requestRecordAudioPermission();
        } else {
            startRecording();
        }

        sbListener();
        setTuning();
        setReferencePitch();
        //animationView = findViewById(R.id.lottie_view);
        //animationView.playAnimation();

        getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public void myClick2(View v){
        switch (v.getId()){
            case R.id.btn_back:
                finish();
        }
    }

    @Override
    public void onProgressUpdate(PitchDifference pitchDifference) {
        TunerView tunerView = this.findViewById(R.id.pitch);
        KeyView keyView = this.findViewById(R.id.keyview);

        tunerView.setPitchDifference(pitchDifference);
        tunerView.invalidate();
        keyView.setPitchDifference(pitchDifference);//关键所在
        keyView.invalidate();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startRecording();
                } else {
                    AlertDialog alertDialog = new Builder(ButtonActivity.this).create();
                    alertDialog.setTitle(R.string.permission_required);
                    alertDialog.setMessage(getString(R.string.microphone_permission_required));
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok),
                            (dialog, which) -> {
                                dialog.dismiss();
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    finishAffinity();
                                } else {
                                    finish();
                                }
                            });
                    alertDialog.show();
                }
            }
        }
    }

    private void startRecording() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        ListenerFragment listenerFragment = (ListenerFragment)
                fragmentManager.findFragmentByTag(TAG_LISTENER_FRAGMENT);

        if (listenerFragment == null) {
            listenerFragment = new ListenerFragment();
            fragmentManager
                    .beginTransaction()
                    .add(listenerFragment, TAG_LISTENER_FRAGMENT)
                    .commit();
        }
    }

    private void sbListener()
    {
        com.suke.widget.SwitchButton Ref_Pitch_Button = (com.suke.widget.SwitchButton)
                findViewById(R.id.switch_button1);
        final SharedPreferences btn_state_pref=getSharedPreferences(PREFS_FILE,MODE_PRIVATE);
        swiBtn_state=btn_state_pref.getBoolean(SWITCH_BUTTON_STATE,false);
        Ref_Pitch_Button.setChecked(swiBtn_state);//设置为真，即默认为真
        //Ref_Pitch_Button.isChecked();//被选中

        Ref_Pitch_Button.toggle();     //开关状态
        Ref_Pitch_Button.toggle(true);//开关有动画
        Ref_Pitch_Button.setShadowEffect(false);//禁用阴影效果
        Ref_Pitch_Button.setEnabled(true);//false为禁用按钮
        Ref_Pitch_Button.setEnableEffect(true);//false为禁用开关动画
        Ref_Pitch_Button.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                final SharedPreferences preferences = getSharedPreferences(PREFS_FILE,
                        MODE_PRIVATE);
                if(Ref_Pitch_Button.isChecked())
                {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt(REFERENCE_PITCH, 442);//先修改REFERNECE_PITCH的键值，再调用setReferencePitch();
                    editor.apply();

                    SharedPreferences.Editor editor2 = preferences.edit();
                    editor2.putBoolean(SWITCH_BUTTON_STATE,true);
                    editor2.apply();
                }
                else {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt(REFERENCE_PITCH, 440);//先修改REFERNECE_PITCH的键值，再调用setReferencePitch();
                    editor.apply();

                    SharedPreferences.Editor editor2 = preferences.edit();
                    editor2.putBoolean(SWITCH_BUTTON_STATE,false);
                    editor2.apply();
                }
                setReferencePitch();
                Toast.makeText(ButtonActivity.this, "标准音频率成功设置为："+String.valueOf(referencePitch), Toast.LENGTH_LONG).show();
            }
        });

        com.suke.widget.SwitchButton SciOrSol_Button = (com.suke.widget.SwitchButton)
                findViewById(R.id.switch_button2);
        final SharedPreferences btn_state_pref2=getSharedPreferences(PREFS_FILE,MODE_PRIVATE);
        swiBtn_state2=btn_state_pref.getBoolean(SWITCH_BUTTON_STATE2,false);
        SciOrSol_Button.setChecked(swiBtn_state2);//设置为真，即默认为真
        //Ref_Pitch_Button.isChecked();//被选中

        SciOrSol_Button.toggle();     //开关状态
        SciOrSol_Button.toggle(true);//开关有动画
        SciOrSol_Button.setShadowEffect(false);//禁用阴影效果
        SciOrSol_Button.setEnabled(true);//false为禁用按钮
        SciOrSol_Button.setEnableEffect(true);//false为禁用开关动画
        SciOrSol_Button.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                final SharedPreferences preferences = getSharedPreferences(PREFS_FILE,
                        MODE_PRIVATE);
                if(SciOrSol_Button.isChecked())
                {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean(USE_SCIENTIFIC_NOTATION,  false);
                    editor.apply();

                    SharedPreferences.Editor editor2 = preferences.edit();
                    editor2.putBoolean(SWITCH_BUTTON_STATE2,true);
                    editor2.apply();
                }
                else{
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean(USE_SCIENTIFIC_NOTATION, true);
                    editor.apply();

                    SharedPreferences.Editor editor2 = preferences.edit();
                    editor2.putBoolean(SWITCH_BUTTON_STATE2,false);
                    editor2.apply();
                }

                Toast.makeText(ButtonActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setReferencePitch() {
        final SharedPreferences preferences = getSharedPreferences(PREFS_FILE,
                MODE_PRIVATE);
        referencePitch = preferences.getInt(REFERENCE_PITCH, 440);
    }

    private void setTuning() {
        final SharedPreferences preferences = getSharedPreferences(PREFS_FILE,
                MODE_PRIVATE);
        tuningPosition = preferences.getInt(CURRENT_TUNING, 0);

        //int textColorDark = getResources().getColor(R.color.colorTextDark);

        //if (isDarkModeEnabled) {
        //    spinner.setTextColor(textColorDark);
        //    spinner.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        //    spinner.setTextColor(textColorDark);
        //    spinner.setArrowColor(textColorDark);
        //}
    }

    private void requestRecordAudioPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},
                RECORD_AUDIO_PERMISSION);
    }


}